<template>
  <div class="category-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>商品分类管理</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          @click="addRootCategory"
        >
          添加根分类
        </el-button>
      </div>

      <el-tree
        :data="categoryTree"
        :props="defaultProps"
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
        :highlight-current="true"
        @node-click="handleNodeClick"
        ref="categoryTree"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span v-if="data.type !== 3" class="node-actions">
            <el-button
              type="text"
              size="mini"
              @click.stop="addChildCategory(data)"
            >
              增加
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click.stop="deleteCategory(data, node)"
              :disabled="node.childNodes && node.childNodes.length > 0"
            >
              删除
            </el-button>
          </span>
          <span v-else class="node-actions">
            <el-button
              type="text"
              size="mini"
              @click.stop="deleteCategory(data, node)"
              :disabled="node.childNodes && node.childNodes.length > 0"
            >
              删除
            </el-button>
          </span>
        </span>
      </el-tree>
    </el-card>

    <!-- 修改分类的对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="分类名称">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类" v-if="editForm.type !== 1">
          <el-cascader
            v-model="editForm.parentIdPath"
            :options="categoryOptions"
            :props="{ checkStrictly: true, value: 'id', label: 'name' }"
            clearable
            style="width: 100%"
            @change="handleParentChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="分类类型">
          <el-select v-model="editForm.type" disabled>
            <el-option :label="typeLabel" :value="editForm.type"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      categoryTree: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      dialogVisible: false,
      dialogTitle: "修改分类",
      editForm: {
        id: "",
        name: "",
        parentId: 0,
        parentIdPath: [],
        type: 1,
      },
      categoryOptions: [],
      dataOperationToken: "",
    };
  },
  created() {
    this.loadCategoryTree();
  },
  computed: {
    typeLabel() {
      switch (this.editForm.type) {
        case 1:
          return "一级分类";
        case 2:
          return "二级分类";
        case 3:
          return "三级分类";
        default:
          return "未知分类";
      }
    },
  },
  methods: {
    // 加载分类树数据
    async loadCategoryTree() {
      try {
        const response = await axios.get("/api/category/getCategoryTree");
        console.log("树状图数据", response);
        if (response.data.code === 200) {
          this.categoryTree = response.data.categoryTree;
          this.generateCategoryOptions();
        }
      } catch (error) {
        this.$message.error("加载分类树失败: " + error.message);
      }
    },

    // 生成级联选择器选项
    generateCategoryOptions() {
      const generateOptions = (nodes) => {
        return nodes
          .filter((node) => node.id !== this.editForm.id) // 只排除自己
          .map((node) => {
            const option = {
              id: node.id,
              name: node.name,
              // 禁用自己（防止选择自己为父级）
              disabled: node.id === this.editForm.id,
            };

            // 只展开到二级分类（不显示三级分类的子级）
            if (node.children && node.type < 2) {
              option.children = generateOptions(node.children);
            }
            return option;
          });
      };
      this.categoryOptions = generateOptions(this.categoryTree);
    },

    // 判断一个节点是否是某个id的祖先节点（即是否是其子节点）
    isDescendant(node, targetId) {
      if (!node.children) return false;

      // 检查直接子节点
      if (node.children.some((child) => child.id === targetId)) {
        return true;
      }

      // 递归检查子节点的子节点
      return node.children.some((child) => this.isDescendant(child, targetId));
    },

    // 添加根分类
    async addRootCategory() {
      try {
        const { value } = await this.$prompt("请输入根分类名称", "添加根分类");
        const res = await axios.post("/api/category/addCategory", {
          name: value,
          parentId: 0,
          type: 1,
        });
        this.loadCategoryTree();
        this.$message.success(res.data.data);
      } catch (error) {
        if (error !== "cancel") {
          this.$message.error("添加失败: " + error.message);
        }
      }
    },

    // 添加子分类
    async addChildCategory(parentData) {
      try {
        const { value } = await this.$prompt(
          "请输入子分类名称",
          `在 ${parentData.name} 下添加子分类`
        );
        const res = await axios.post("/api/category/addCategory", {
          name: value,
          parentId: parentData.id,
          type: parentData.type + 1,
        });
        this.loadCategoryTree();
        if(res.data.code===500){
          this.$message.error(res.data.data);
          return;
        }
        this.$message.success(res.data.data);
      } catch (error) {
        if (error !== "cancel") {
          this.$message.error("添加失败: " + error.message);
        }
      }
    },

    // 点击节点修改分类
    handleNodeClick(data) {
      this.editForm = {
        id: data.id,
        name: data.name,
        parentId: data.parentId,
        parentIdPath: this.getParentIdPath(data),
        type: data.type,
      };
      // 生成选项时排除自己和自己的子节点
      this.generateCategoryOptions();

      // 一级分类不需要选择父级
      if (data.type === 1) {
        this.editForm.parentIdPath = [];
      }

      this.dialogVisible = true;
    },
    // 处理父级分类变化
    handleParentChange(value) {
      const parentId = value?.at(-1) || 0;
      this.editForm.parentId = parentId;

      // 直接根据父级类型设置当前类型（不再特殊处理）
      const parentType = this.getParentType(parentId);
      this.editForm.type = parentType + 1;
    },

    // 获取父级的类型
    getParentType(parentId) {
      if (!parentId || parentId === 0) return 0;

      const findNode = (nodes) => {
        for (const node of nodes) {
          if (node.id === parentId) return node;
          if (node.children) {
            const found = findNode(node.children);
            if (found) return found;
          }
        }
        return null;
      };

      const parentNode = findNode(this.categoryTree);
      return parentNode ? parentNode.type : 0;
    },

    // 获取父级ID路径
    getParentIdPath(data) {
      if (data.type === 1) return [];

      const findPath = (nodes, targetId, path = []) => {
        for (const node of nodes) {
          if (node.id === targetId) {
            return path.concat(node.id);
          }
          if (node.children) {
            const found = findPath(
              node.children,
              targetId,
              path.concat(node.id)
            );
            if (found) return found;
          }
        }
        return null;
      };

      return findPath(this.categoryTree, data.parentId) || [];
    },

    // 确认修改
    async confirmEdit() {
      try {
        const { level1Id, level2Id, level3Id } = this.getCategoryLevelPath(
          this.editForm.id,
          this.editForm.parentId,
          this.editForm.type,
          this.editForm.parentIdPath // 新增：传递路径数组
        );

        const res = await axios.post(
          "/api/category/updateCategory",
          this.editForm,
          { params: { level1Id, level2Id, level3Id } }
        );

        // 3. 处理响应
        if (res.data.code === 200) {
          this.loadCategoryTree(); // 刷新分类树
          this.dialogVisible = false;
          this.$message.success("分类修改成功");
        } else {
          this.$message.error(res.data.msg);
        }
      } catch (error) {
        this.$message.error("修改失败: " + error.message);
      }
    },

    //计算分类level1、level2、level3的方法
    getCategoryLevelPath(currentId, parentId, type, parentIdPath) {
      let level1Id = 0,
        level2Id = 0,
        level3Id = 0;

      if (type === 1) {
        level1Id = currentId; // 一级分类
      } else if (type === 2) {
        level1Id = parentId; // 二级分类：父级是level1
        level2Id = currentId;
      } else if (type === 3) {
        //直接从 parentIdPath 提取各级ID
        level1Id = parentIdPath[0] || 0; // 一级分类ID（路径第一个元素）
        level2Id = parentIdPath[1] || 0; // 二级分类ID（路径第二个元素）
        level3Id = currentId; // 三级分类ID（自身）
      }

      console.log("计算后的层级ID:", level1Id, level2Id, level3Id);
      return { level1Id, level2Id, level3Id };
    },

    findNodeById(nodes, id) {
      for (const node of nodes) {
        if (node.id === id) return node;
        if (node.children) {
          const found = this.findNodeById(node.children, id);
          if (found) return found;
        }
      }
      return null;
    },

    // 删除分类
    async deleteCategory(data) {
      try {
        await this.$confirm(`确定删除分类 "${data.name}"?`, "提示", {
          type: "warning",
        });
        // const token = await this.getSecureToken(data.id);

        const response = await axios.delete(
          // `/api/category/deleteCategory/${data.id}&${data.type}&${token}`
          `/api/category/deleteCategory/${data.id}&${data.type}`
        );
        console.log(response);

        // 根据后端返回的success字段判断操作是否成功
        if (response.data.code === 200) {
          this.$message.success(response.data.data);
          this.loadCategoryTree(); // 刷新分类树
        } else {
          // 显示后端返回的具体错误信息
          this.$message.error(response.data.msg);
        }
      } catch (error) {
        if (error.response) {
          // 请求已发出，服务器响应状态码不在2xx范围内
          if (error.response.data && error.response.data.data) {
            this.$message.error(error.response.data.data);
          } else {
            this.$message.error(
              `删除失败: ${error.response.status} ${error.response.statusText}`
            );
          }
        }
      }
    },
    // async getSecureToken(id) {
    //   try {
    //     const response = await axios.get(
    //       `/api/category/getCategoryToken/${id}`
    //     );
    //     if (response.data && response.data.msg) {
    //       return response.data.msg;
    //     } else {
    //       throw new Error("返回值错误，检查返回数据结构");
    //     }
    //   } catch (error) {
    //     console.error("拿回token错误:", error);
    //     throw error;
    //   }
    // },
  },
};
</script>

<style scoped>
.category-container {
  padding: 20px;
}

.box-card {
  max-width: 800px;
  margin: 0 auto;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.node-actions {
  margin-left: 10px;
}

.node-actions .el-button {
  padding: 0 5px;
}

/* 禁用按钮样式 */
.node-actions .el-button.is-disabled {
  color: #c0c4cc;
  cursor: not-allowed;
}
</style>